package com.leyou.user.web;

import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * description: 用户相关接口
 * @author 朱正磊
 * @date 2021-04-16 15:51:33
 */
@RestController
public class UserController {

    @Resource
    private UserService userService;

    /**
     * description: 注册请求参数校验
     * @author 朱正磊
     * @date 2021-04-16 15:59:51
     * @param data 待校验的数据
     * @param type 待校验的数据类型，1-用户名；2-手机号码
     * @return 如果校验成功则返回true，否则返回false
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkData(
            @PathVariable("data") String data, @PathVariable("type") Integer type) {
        return ResponseEntity.ok(userService.checkData(data, type));
    }

    /**
     * description: 发送手机短信验证码
     * @author 朱正磊
     * @date 2021-04-16 16:39:00
     * @param phone 手机号码
     * @return 无返回值
     */
    @PostMapping("code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone") String phone) {
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * description: 用户注册
     * @author 朱正磊
     * @date 2021-04-16 18:54:33
     * @param user 用户对象
     * @param result 验证结果对象
     * @param code 短信验证码
     * @return 无返回值
     */
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code) {
        if (result.hasFieldErrors()) {
            throw new RuntimeException(result.getFieldErrors().stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("|")));
        }
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * description: 根据用户名和密码查询用户
     * @author 朱正磊
     * @date 2021-04-17 17:01:28
     * @param username 用户名
     * @param password 密码
     * @return 返回用户信息
     */
    @GetMapping("query")
    public ResponseEntity<User> queryUserByUsernameAndPassword(@RequestParam("username") String username,
                                                               @RequestParam("password") String password) {
        return ResponseEntity.ok(userService.queryUserByUsernameAndPassword(username, password));
    }

}
